package com.mlk.rbac.Service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.mlk.core.exception.ParamException;
import com.mlk.core.util.ServerResponse;
import com.mlk.core.util.SessionUtils;
import com.mlk.rbac.Service.SysUserRoleService;
import com.mlk.rbac.mapper.SysUserRoleMapper;
import com.mlk.rbac.po.SysRoleUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;


/**
 * 用户角色服务
 * @author xulu
 *
 */
@Service
@Slf4j
public class SysUserRoleServiceImpl implements SysUserRoleService {
	
	@Resource
	private SysUserRoleMapper sysUserRoleMapper;
	
	@Override
	public ServerResponse roleList(Integer id) {
		if(id == null) {
			return ServerResponse.fail("传递的参数id不能为空");
		}
		
		List<SysRoleUser> selectList = this.sysUserRoleMapper.selectList(new  EntityWrapper<>(SysRoleUser.builder().userId(id).build()));
		
		return ServerResponse.ok(selectList);
	}
	
	@Override
	@Transactional
	public ServerResponse roleAllocate(Integer id, String roleIds) {
		if(id == null) {
			return ServerResponse.fail("用户的id不能为空");
		}
		
		List<SysRoleUser> roleUsers = adapt(id,roleIds);
		
		// 首先删除掉之前的内容
		this.sysUserRoleMapper.delete(new EntityWrapper<>(SysRoleUser.builder().userId(id).build()));
		
		//然后新添加内容
		if(roleUsers.size() > 0) {
			int count = this.sysUserRoleMapper.insertBatchRoleUsers(roleUsers);
			
			if(count != roleUsers.size()) {
				return ServerResponse.fail("更新角色信息出现问题");
			}
		}
		
		return ServerResponse.ok("更新角色成功");
	}
	
	private List<SysRoleUser> adapt(Integer id, String roleIds){
		
		List<SysRoleUser> userRoles = Lists.newArrayList();;
		try {
			
			String[] roles = StringUtils.split(roleIds, ",");
			if(roles != null && roles.length > 0) {
				for(String roleId : roles) {
					userRoles.add(SysRoleUser.builder().userId(id).roleId(Integer.parseInt(roleId)).operateTime(new Date()).operator(SessionUtils.getSysUser().getName()).build());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("传入的角色id列表出现问题,roleIds={}",roleIds);
			throw new ParamException("传入的角色id列表出现问题");
		}
		
		return userRoles;
	}
	
}
